package com.imooc.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import com.imooc.utils.extend.AliyunResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 阿里云短信工具发送类
 */
@Component
public class SMSUtils {

    /**
     * 注入读取的阿里云密钥信息
     */
    @Autowired
    public AliyunResource aliyunResource;

    /**
     * 发送短信（单条信息）
     *
     * @param mobile 手机号
     * @param code   验证码
     */
    public void sendSMS(String mobile, String code) {
        // 地区编号（查看自己的阿里云）、密钥id、密钥secret
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-hangzhou",
                aliyunResource.getAccessKeyID(),
                aliyunResource.getAccessKeySecret()
        );
        IAcsClient client = new DefaultAcsClient(profile);

        // 不是企业用户只能测试使用，签名和模板都是需要企业资格
        SendSmsRequest request = new SendSmsRequest();
        request.setSignName("阿里云短信测试");
        request.setTemplateCode("SMS_154950909");
        request.setPhoneNumbers(mobile);
        request.setTemplateParam("{\"code\":\"" + code + "\"}");

        try {
            SendSmsResponse response = client.getAcsResponse(request);
            System.out.println(new Gson().toJson(response));
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
    }
}
